<?php

class BaseController extends Controller
{

    /**
     * Setup the layout used by the controller.
     *
     * @return void
     */
    protected function setupLayout()
    {
        if ( ! is_null($this->layout)) {
            $this->layout = View::make($this->layout);
        }
    }

    /**
     * 简单返回错误提示
     * @param $message
     * @return \Illuminate\Http\JsonResponse
     */
    public static function failResponse($message)
    {
        $response = null;
        if ($message instanceof \Illuminate\Support\MessageBag) {

            $messages = $message->toArray();
            foreach ($messages as $fieldName => $fieldMessage) {
                $toString = null;
                foreach ($fieldMessage as $single) {
                    $toString.= $single;
                }
                $response[$fieldName] = $toString;
            }

        } else {
            $response = $message;
        }

        return Response::json([
            'status' => 'failure',
            'message' => $response
        ]);
    }

    /**
     * 简单返回成功提示
     * @return \Illuminate\Http\JsonResponse
     */
    public static function successResponse()
    {
        return Response::json([
            'status' => 'success',
            'message' => '操作成功'
        ]);
    }

    /**
     * 对post数据过滤
     * @param $postData
     * @param $retains
     * @return array
     */
    protected function postFilter($postData, $retains)
    {
        $filtered = [];
        foreach ($retains as $check) {
            if (isset($postData[$check])) {
                $filtered[$check] = $postData[$check];
            } else {
                $filtered[$check] = null;
            }
        }

        return $filtered;
    }

}
